package com.yanghongyue.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.yanghongyue.reggie.common.BaseContext;
import com.yanghongyue.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author HongyueYang
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    //创建路径匹配对象
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求对象
        HttpServletRequest req = (HttpServletRequest) request;
        //获取响应对象
        HttpServletResponse resp = (HttpServletResponse) response;
        //通过请求对象获取本次请求过来的地址
        String requestURI = req.getRequestURI();
        System.out.println("拦截请求地址===>" + requestURI);
        //定义不需要拦截的地址
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断本次请求是否需要处理
        boolean check = this.check(urls, requestURI);
        //如果不需要处理则直接放行
        if (check) {
            chain.doFilter(req, response);
            return;
        }
        //从session中获取登录时存入的员工id
        Long empId = (Long) req.getSession().getAttribute("empId");
        //如果id存在，代表登录
        if (empId != null) {
            //如果已经登录，将当前员工的id存入到线程变量中
            BaseContext.setCurrentId(empId);
            //放行
            chain.doFilter(req, response);
            return;
        }

        //从session中获取登录时存入的用户id
        Long userId = (Long) req.getSession().getAttribute("userId");
        //如果id存在，代表登录
        if (userId != null) {
            //如果已经登录，将当前员工的id存入到线程变量中
            BaseContext.setCurrentId(userId);
            //放行
            chain.doFilter(req, response);
            return;
        }

        //如果用户未登录，返回登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    //判断路径是否匹配的方法
    private boolean check(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) {
                return match;
            }
        }
        return false;
    }

}
